// src/brands/weibo/WeiboReal.ts
import axios from 'axios';
import { getBrandConfig } from '../getBrandConfig';
import { AbstractPlatform } from '../AbstractPlatform';
import {AppDataSource} from "../../config/database";
import {BranchAccount} from "../../entity/BranchAccount";

export class MideaReal extends AbstractPlatform {
    private config = getBrandConfig("midea");

    async exchangeToken(code: string): Promise<{ access_token: string; expires_in: number }> {
        this.logExchange('midea', false);

        // TODO: 现实需根据平台实际url与获取api方法更改代码逻辑
        const config = getBrandConfig('midea');
        const response = await axios.post('https://api.midea.com/oauth2/access_token', {
            code,
            app_id: config.app_id,
            app_secret: config.app_secret
        });

        return {
            access_token: response.data.access_token,
            expires_in: response.data.expires_in
        };
    }

    async revokeToken(token: string): Promise<void> {
        const config = getBrandConfig('xiaomi');
        await axios.post('https://api.midea.com/oauth2/revoke_token', {
            access_token: token,
            app_id: config.app_id,
            app_secret: config.app_secret
        });
    }

    async refreshToken(userId: string, oldToken: string): Promise<{ access_token: string; expires_in: number }> {
        const config = getBrandConfig('midea');
        const response = await axios.post('https://api.midea.com/oauth2/rfresh_token', {
            user_id: userId,
            old_token: oldToken,
            app_id: config.app_id,
            app_secret: config.app_secret
        });

        return {
            access_token: response.data.access_token,
            expires_in: response.data.expires_in
        };
    }

    async getDeviceList(accessToken: string): Promise<{
        did: string;
        name: string;
        type: string;
        online: boolean;
    }[]> {
        const url = 'http://localhost:3001/midea/devices';
        const clientId = this.config.app_id;

        const res = await fetch(url, {
            method: 'GET',
            headers: {
                Authorization: `Bearer ${accessToken}`,
                ClientId: clientId
            }
        });

        const json = await res.json();

        if (res.status !== 200 || json.code !== 200) {
            throw new Error(`获取美的设备列表失败: ${json.message || res.status}`);
        }

        const applianceList = json.data.applianceList || [];

        return applianceList.map((item: any) => ({
            did: item.virtualId,
            name: item.name,
            type: item.type,
            online: item.online
        }));

    }

    async subscribeDevice(accessToken: string, deviceId: string): Promise<void> {
        const reqId = Date.now().toString();
        const url = 'http://localhost:3001/midea/device/subscribe';

        const res = await fetch(url, {
            method: 'POST',
            headers: {
                Authorization: accessToken,
                ClientId: this.config.app_id,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                reqId,
                applianceCode: deviceId
            })
        });

        const json = await res.json();

        if (res.status !== 200) {
            throw new Error(`Midea订阅失败：HTTP状态码 ${res.status}`);
        }

        if (json.code === 1300) {
            throw new Error(`Midea订阅失败：设备不存在`);
        }

        if (json.code === 1006) {
            throw new Error(`Midea订阅失败：用户验证失败`);
        }

        console.log(`[SUBSCRIBE] Midea 设备 ${deviceId} 订阅成功 (reqId: ${reqId})`);
    }

    async revokeDeviceSubscription(userId: string, deviceId: string): Promise<void> {
        const reqId = Date.now().toString();
        const tokenRepo = AppDataSource.getRepository(BranchAccount);
        const record = await tokenRepo.findOne({where: {userId, brand: 'midea'}});

        if (!record) throw new Error(`未找到美的授权信息`);

        const res = await fetch('http://localhost:3001/midea/device/subscribe/cancel', {
            method: 'POST',
            headers: {
                Authorization: record.token,
                ClientId: this.config.app_id,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                reqId,
                applianceCode: deviceId
            })
        });

        const json = await res.json();

        if (res.status !== 200) {
            throw new Error(`Midea取消订阅失败: ${res.status}`);
        }

        if (json.code === 1300) {
            throw new Error(`设备不存在`);
        } else if (json.code === 1006) {
            throw new Error(`用户验证失败`);
        }

        console.log(`[UNSUB] Midea 设备 ${deviceId} 取消订阅成功`);
    }

}
